import {
  getAllMenus as getAllMenusApi,
  MenuData,
  addMenu as addMenuApi,
  removeMenuById,
  updateMenuById,
  updateBulkMenu as updateBulkMenuApi
} from "@/api/menu"
import { generateTree } from "@/utils/generateTree"
export interface ITreeItemData extends MenuData {
  children?: ITreeItemData[]
}

export interface IMenusState {
  menuTreeData: Array<ITreeItemData>
  menuList: Array<MenuData>
}

export const useMenuStore = defineStore("menu", () => {
  const state = reactive<IMenusState>({
    menuList: [],
    menuTreeData: []
  })
  const getAllMenuList = async () => {
    const response = await getAllMenusApi()
    const { data } = response
    state.menuList = data
    const treeData = generateTree([...data])
    state.menuTreeData = treeData
  }

  const appendMenu = async (data: ITreeItemData) => {
    const res = await addMenuApi(data)
    if (res.code === 0) {
      const node = { ...data }
      state.menuList.push(node)
      const treeData = generateTree([...state.menuList])
      state.menuTreeData = [...treeData]
      return node
    }
  }

  const removeMenu = async (data: ITreeItemData) => {
    const res = await removeMenuById(data.id!)
    if (res.code === 0) {
      const idx = state.menuList.findIndex((menu) => menu.id === data.id)
      state.menuList.splice(idx, 1)
      const treeData = generateTree([...state.menuList])
      state.menuTreeData = [...treeData]
    }
  }

  const updateMenu = async (data: Partial<MenuData>) => {
    const res = await updateMenuById(Number(data.id), data)
    if (res.code === 0) {
      await getAllMenuList()
      return true
    }
  }

  const updateBulkMenu = async () => {
    state.menuTreeData.forEach((menu, index) => {
      menu.sort_id = index
    })

    const menuList = state.menuTreeData.map((menu) => {
      const temp = { ...menu }
      delete temp.children
      return temp
    })
    await updateBulkMenuApi(menuList)
  }
  return {
    state,
    getAllMenuList,
    appendMenu,
    removeMenu,
    updateMenu,
    updateBulkMenu
  }
})
